package org.example.day08;

/**
 * 第三章节3.1.16: 方法wait(long)被唤醒后继续运行的条件
 *      注意: 如果被唤醒后，没有获取到锁，会继续等到，直到获取到锁为止.
 */
public class MyThread3 {
    public void testMethod(){
        try {
            synchronized (this){
                System.out.println("wait begin time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
                wait(5000); //释放锁5s后还不能继续执行，得等longTimeSyn()释放锁才行.
                System.out.println("wait end time = " + System.currentTimeMillis() + " ThreadName = " + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    synchronized public void longTimeSyn(){
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread3 m3 = new MyThread3();
        Thread3A[] array = new Thread3A[10];
        for (int i = 0; i < 10; i++) {
            array[i] = new Thread3A(m3);
        }
        for (int i = 0; i < 10; i++) {
            array[i].start();
        }
        Thread3B tb = new Thread3B(m3);
        tb.start();
    }
}

class Thread3A extends Thread{
    private MyThread3 m3;

    public Thread3A(MyThread3 m3) {
        this.m3 = m3;
    }

    @Override
    public void run() {
        m3.testMethod();
    }
}

class Thread3B extends Thread{
    private MyThread3 m3;

    public Thread3B(MyThread3 m3) {
        this.m3 = m3;
    }

    @Override
    public void run() {
        m3.longTimeSyn();
    }
}